/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: response_builder.h
 *
 * Purpose: a builder can be make a reponse instance
 *
 * Developer:
 *   wen.gu , 2021-08-31
 *
 * TODO:
 *
 ***************************************************************************/

/******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#ifndef __ICPP_COM_RESPONSE_BUILDER_H__
#define __ICPP_COM_RESPONSE_BUILDER_H__
#include <functional>
#include <memory>
#include <future>

#include "icpp/com/types.h"
#include "icpp/com/response.h"
/******************************************************************************
 **    MACROS
 ******************************************************************************/


/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/
namespace icpp
{
namespace com
{


/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/

template<typename ResponseType, typename ErrorType = core::IcppErrc>
class ResponseBuilder final
{
public:
    using ValueType = Result<ResponseType, ErrorType>;
    using ValueTypePtr = std::shared_ptr<ValueType>;

    using InternalState = internal_impl::InternalState<ResponseType, ErrorType>;
    using InternalStatePtr = std::shared_ptr<InternalState>;
    using ResponseBuilderPtr = std::shared_ptr<ResponseBuilder<ResponseType, ErrorType> >;
private:
    InternalStatePtr internal_state_ = nullptr;
    std::mutex lock_;
public:
    ResponseBuilder()
    :internal_state_(std::make_shared<InternalState>())
    {
        /** todo something */
    }

    ResponseBuilder(ResponseBuilder&& other)
    :internal_state_(std::move(other.internal_state_))
    {
        /** todo something */
    }


    ~ResponseBuilder()
    {
        /** todo something */
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);
        if (!is->is_complete_) /**if not set value or error yet, then set a error to shared state */       
        {
            processHandler(is, std::make_shared<ValueType>(core::IcppErrc::BrokenResponse));   
        }
    }

public:
    ResponseBuilder& operator= (ResponseBuilder&& other)
    {
        internal_state_ = std::move(internal_state_);
    }

public:
    ResponseBuilder(const ResponseBuilder& other) = delete;
    ResponseBuilder& operator= (const ResponseBuilder& other) = delete;

public:
    bool setValue(ResponseType&& val)
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>(std::forward<ResponseType>(val)));   
    }

    bool setValue(const ResponseType& val)
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>(val));    
    }

    bool setError(const ErrorType& err)
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>(err));    
    }

    bool setError(ErrorType&& err)
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>(std::forward<ErrorType>(err)));    
    }

public:
    bool isComplete() const 
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);
        return is->is_complete_;
    }

public:
    Response<ResponseType, ErrorType> getResponse()
    {
        return std::move(Response<ResponseType, ErrorType>(internal_state_));
    }

private:
    bool processHandler(InternalState* is, ValueTypePtr val_ptr)
    {
        is->val_ptr_ = val_ptr;
        if (is->val_ptr_ == nullptr)
        { /** todo, refine me?? */
            return false;
        }

        is->is_complete_ = true;
        for (auto it: is->handlers_)
        {
            it(*(is->val_ptr_.get()));
        }

        is->handlers_.clear();
        is->cond_.notify_all();
        return true;           
    }

};


///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

template<typename ErrorType>
class ResponseBuilder<void, ErrorType> final
{
public:
    using ValueType = Result<void, ErrorType>;
    using ValueTypePtr = std::shared_ptr<ValueType>;

    using InternalState = internal_impl::InternalState<void, ErrorType>;
    using InternalStatePtr = std::shared_ptr<InternalState>;
    using ResponseBuilderPtr = std::shared_ptr<ResponseBuilder<void, ErrorType> >;
private:
    InternalStatePtr internal_state_ = nullptr;
    std::mutex lock_;
public:
    ResponseBuilder()
    :internal_state_(std::make_shared<InternalState>())
    {
        /** todo something */
    }

    ResponseBuilder(ResponseBuilder&& other)
    :internal_state_(std::move(other.internal_state_))
    {
        /** todo something */
    }


    ~ResponseBuilder()
    {
        /** todo something */
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);
        if (!is->is_complete_) /**if not set value or error yet, then set a error to shared state */       
        {
            processHandler(is, std::make_shared<ValueType>(core::IcppErrc::BrokenResponse));   
        }
    }

public:
    ResponseBuilder& operator= (ResponseBuilder&& other)
    {
        internal_state_ = std::move(internal_state_);
    }

public:
    ResponseBuilder(const ResponseBuilder& other) = delete;
    ResponseBuilder& operator= (const ResponseBuilder& other) = delete;

public:
    bool setValue()
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>());   
    }

    bool setError(const ErrorType& err)
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>(err));    
    }

    bool setError(ErrorType&& err)
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);

        if (is->is_complete_) /** already set value, then just return false */
        {
            return false;
        }

        return processHandler(is, std::make_shared<ValueType>(std::move(err)));    
    }

public:
    bool isComplete() const 
    {
        InternalState* is = internal_state_.get();
        core::AutoLock al(is->lock_);
        return is->is_complete_;
    }

public:
    Response<void, ErrorType> getResponse()
    {
        return std::move(Response<void, ErrorType>(internal_state_));
    }

private:
    bool processHandler(InternalState* is, ValueTypePtr val_ptr)
    {
        is->val_ptr_ = val_ptr;
        if (is->val_ptr_ == nullptr)
        { /** todo, refine me?? */
            return false;
        }

        is->is_complete_ = true;
        for (auto it: is->handlers_)
        {
            it(*(is->val_ptr_.get()));
        }

        is->handlers_.clear();
        is->cond_.notify_all();
        return true;           
    }

};

} /** namespace com */
} /** namespace icpp */

#endif /** !__ICPP_COM_RESPONSE_BUILDER_H__ */

